<template>
  <div class="card-box">
    <!-- 设计完成预览表单弹窗 -->
    <public-dialog v-model="isDialog" :title="props.dialogTitle" :before-close="closeDialog" @confirmDialog="confirmDialog">
      <el-row class="center-board-row" :gutter="formConf.gutter">
        <el-form
          ref="formRef"
          :style="{ width: '100%' }"
          :size="formConfigRef.size"
          :label-position="formConfigRef.labelPosition"
          :disabled="formConfigRef.disabled"
          :label-width="formConfigRef.labelWidth + 'px'"
          :model="formData"
          :rules="rules"
        >
          <div v-for="(element, index) of props.detailData.styleJson" :key="index">
            <preview-form-item
              :key="element.renderKey"
              :element="element"
              :index="index"
              :active-id="element.formId"
              :form-conf="formConfigRef"
              :drawing-list="props.detailData.styleJson"
              :formData="formData"
            />
          </div>
        </el-form>
      </el-row>
    </public-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { formConf } from "@/config/generator/config.js";
import previewFormItem from "@/components/auto-form-component/preview-form-item.vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  dialogTitle: {
    type: String,
    default: "表单详情",
  },
  detailData: {
    type: Object,
    default: () => ({
      styleJson: [],
    }),
  },
});

const isDialog = computed({
  get() {
    return props.modelValue;
  },
  set() {},
});

const emit = defineEmits(["update:modelValue", "previewFormEvent"]);
const formRef = ref(null);
const formConfigRef = reactive(formConf);
const formData = ref({});
const rules = ref({});

// 弹窗
const closeDialog = () => {
  emit("update:modelValue", false);
};
const confirmDialog = async (type) => {
  // 取消
  if (type === "cancel") {
    closeDialog();
    return;
  }
  // 确认
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      /* 
        阿秋提示：这里还单独暴露了一个 formData 对象，这是表单的标准数据格式，如果觉得props.detailData数据太多，可以取这里的数据
      */
      emit("previewFormEvent", props.detailData, formData.value);
      // closeDialog(); //此方法不能直接关闭，请在外层进行关闭弹窗
    }
  });
};

// 阿秋-20240723
const handleData = (list) => {
  let tagType = {
    "el-input": "blur",
    "el-select": "change",
    "el-radio": "change",
    "el-checkbox": "change",
    "el-cascader": "change",
    "el-date-picker": "change",
    "el-time-picker": "change",
  };
  rules.value = {};
  formData.value = {};
  for (const item of list) {
    formData.value[item.vModel] = item.defaultValue || "";
    if (item.required) {
      let rulesObj = {
        required: true,
        message: item.placeholder || item.label + "不能为空",
        trigger: tagType[item.tag],
      };
      rules.value[item.vModel] = [rulesObj];
      if (item.regList && item.regList.length > 0) {
        for (const itx of item.regList) {
          let cleanedPattern = itx.pattern.replace(/^\/|\/$/g, ""); // 去除字符串首尾的斜杠，new RegExp自带首尾斜杠
          // 直接正则校验格式（element-plus自带的正则校验格式）
          const rulesReg = {
            pattern: new RegExp(cleanedPattern),
            message: itx.message,
          };
          // 自定义方法校验方式（如果有复杂的校验，可以使用这个）
          /* const rulesReg = {
            validator(rule, value, callback) {
              let reg = new RegExp(cleanedPattern);
              if (!reg.test(value)) {
                return callback(new Error(itx.message));
              } else {
                callback();
              }
            },
          }; */
          rules.value[item.vModel].push(rulesReg);
        }
      }
    }
  }
};

watch(
  () => props.detailData.styleJson,
  (newValue, oldValue) => {
    if (newValue) {
      handleData(newValue);
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>

<style lang="scss"></style>
